package com.lagou.handler;

import com.alibaba.fastjson.JSON;
import com.lagou.service.RpcRequest;
import com.lagou.service.UserServiceImpl;
import com.lagou.utils.ApplicationContextUtil;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.concurrent.EventExecutorGroup;
import org.springframework.cglib.reflect.FastClass;
import org.springframework.cglib.reflect.FastMethod;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 自定义的业务处理器
 */
public class UserServiceHandler extends ChannelInboundHandlerAdapter {

    //当客户端读取数据时,该方法会被调用
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        // 客户端发送的是一个 RpcRequest 对象
        System.out.println("服务调用: \n" + JSON.toJSONString(msg));
        RpcRequest msg1 = (RpcRequest) msg;
        Object handler = handler(msg1);
        ctx.writeAndFlush("success");


        //注意:  客户端将来发送请求的时候会传递一个参数:  UserService#sayHello#are you ok
         //1.判断当前的请求是否符合规则
        /*if(msg.toString().startsWith("UserService")){
            //2.如果符合规则,调用实现类货到一个result
            UserServiceImpl service = new UserServiceImpl();
            String result = service.sayHello(msg.toString().substring(msg.toString().lastIndexOf("#")+1));
            //3.把调用实现类的方法获得的结果写到客户端
            ctx.writeAndFlush(result);
        }*/
    }

    private Object handler(RpcRequest request) throws Exception {

        //使用Class.forName进行加载Class文件
        Class<?> clazz = Class.forName(request.getClassName());
        Object serviceBean = ApplicationContextUtil.getBean(clazz);

        Class<?> serviceClass = serviceBean.getClass();

        String methodName = request.getMethodName();

        Class<?>[] parameterTypes = request.getParameterTypes();
        Object[] parameters = request.getParameters();

        Method method = serviceBean.getClass().getMethod(methodName, parameterTypes);
        return method.invoke(serviceBean, parameters);
//        FastClass fastClass = FastClass.create(serviceClass);
//        FastMethod fastMethod = fastClass.getMethod(methodName, parameterTypes);
//
//        return fastMethod.invoke(serviceBean, parameters);
    }

}
